import MonacoEditor, { OnMount } from '@monaco-editor/react'
import {createAta} from '../utils/ata'
import { useContext } from 'react'
import { PlaygroundContext } from '../PlaygroundContext'
export interface Flie{
    name:string
    value:string
    language:string
}
export interface EditorProps {
    file:Flie
    onchange?:()=>void
}
export default function Editor(props:EditorProps) {
    const {selectdFileName,setFiles,files} = useContext(PlaygroundContext)
    const {file} = {...props}


    const handleEditorMount: OnMount = (editor, monaco) => {
        editor.addCommand(monaco.KeyMod.WinCtrl|monaco.KeyMod.Shift,()=>{
            editor.getAction('editor.action.formatDocument')?.run()
        })
        monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
            jsx: monaco.languages.typescript.JsxEmit.Preserve,
            esModuleInterop: true,
        })
        const ata = createAta((code,path)=>{
            monaco.languages.typescript.typescriptDefaults.addExtraLib(code,`file://${path}`)
        })
        editor.onDidChangeModelContent(()=>{
            ata(editor.getValue())
        })
        ata(editor.getValue())
    }
    const handleChange = (data:string|undefined)=>{
        files[selectdFileName].value  = data as string
        setFiles({...files})
    }
    return <MonacoEditor
        height='100%'
        path={file.name}
        language={file.language}
        onMount={handleEditorMount}
        onChange={handleChange}
        value={file.value}
        options={{
            fontSize:14,
            scrollBeyondLastLine:false,
            minimap:{
                enabled:false
            },
            scrollbar:{
                verticalScrollbarSize:6,
                horizontalScrollbarSize:6
            }
        }}
    />
}